package com.example.lin.config;

import com.example.lin.handler.SecurityHandler;
import com.example.lin.service.impl.UserDetailsServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @author Administrator
 */
@Slf4j
@Configuration
//@EnableWebSecurity // 开启SpringSecurity功能
@EnableMethodSecurity // 开启SpringSecurity方法权限控制
public class SecurityConfig {

    @Resource
    private UserDetailsServiceImpl userDetailsService;

    @Bean
    public SecurityHandler handler() {
        return new SecurityHandler();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(AbstractHttpConfigurer::disable)
                .cors(Customizer.withDefaults())
                .authorizeHttpRequests(authorizeRequests -> authorizeRequests
                        .requestMatchers("/login", "/register").anonymous()
//                        .requestMatchers("/user/list").hasAuthority("sys:user:list") // 需要权限的接口
//                        .requestMatchers("/user/save").hasAuthority("sys:user:save")
                        .anyRequest().authenticated() // 其它请求需要认证
                )
                .formLogin(form -> form
//                        .loginPage("/login").permitAll()
                        .successHandler(handler())
                        .failureHandler(handler())
                )
                .logout(logout -> logout
                        .logoutUrl("/logout").permitAll()
                        .logoutSuccessHandler(handler())
                        .disable() // 注销
                )
                .sessionManagement(session -> session
                        .maximumSessions(1) // 最大会话数（登录设备数目）
                        .maxSessionsPreventsLogin(true) // 是否阻止后面的登录
                        .expiredSessionStrategy(handler()) // session过期处理
                )
                .exceptionHandling(exception -> exception
                        .authenticationEntryPoint(handler()) // 未登录处理
                        .accessDeniedHandler(handler()) // 访问拒绝处理
                )
        ;
        return http.build();
    }

    /**
     * 密码加密
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

//    @Bean
//    public AuthenticationProvider authenticationProvider() {
//        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
//        provider.setUserDetailsService(userDetailsService);
//        provider.setPasswordEncoder(passwordEncoder());
//        return provider;
//    }

    @Bean
    public AuthenticationManager authenticationManager() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        return new ProviderManager(daoAuthenticationProvider);
    }
}
